import 'dart:async';
import 'package:flutter/material.dart';
import 'main.dart';


class MApp extends StatelessWidget {
  const MApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MBanner(
        imageUrls: const [
          "assets/images/列表图 1.png",
          "assets/images/列表图 2.png",
          "assets/images/列表图 3.png",
          "assets/images/列表图 4.png",
        ],
      ),
    );
  }
}

// 横幅轮播组件
class MBanner extends StatefulWidget {
  final List<String> imageUrls;
  final double height;

  const MBanner({
    super.key,
    required this.imageUrls,
    this.height = 200,
  });

  @override
  State<MBanner> createState() => _MBannerState();
}

class _MBannerState extends State<MBanner> {
  late PageController _pageController;
  late Timer _timer;
  int _currentPage = 0;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
    _timer = Timer.periodic(const Duration(seconds: 3), (timer) {
      if (_pageController.hasClients) {
        int nextPage = (_currentPage + 1) % widget.imageUrls.length;
        _pageController.animateToPage(
          nextPage,
          duration: const Duration(milliseconds: 300),
          curve: Curves.ease,
        );
      }
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: widget.height,
      width: double.infinity,
      child: Stack(children: [
        PageView.builder(
          controller: _pageController,
          onPageChanged: (i) {
            _currentPage = i;
            setState(() {});
          },
          itemCount: null,
          itemBuilder: (context, index) {
            return Container(
              width: double.infinity,
              height: double.infinity,
              child: Image.asset(
                widget.imageUrls[index % widget.imageUrls.length],
                fit: BoxFit.cover,
              ),
            );
          },
        ),
        Align(
          alignment: Alignment.bottomCenter,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: widget.imageUrls
                .asMap()
                .map((key, value) {
              return MapEntry(
                key,
                Container(
                  margin: const EdgeInsets.all(12),
                  width: 10,
                  height: 10,
                  color: key == _currentPage % widget.imageUrls.length
                      ? Colors.yellow
                      : Colors.white,
                ),
              );
            })
                .values
                .toList(),
          ),
        ),
      ]),
    );
  }
}